# -*- coding:utf-8 -*-
import re
import os
import time
import json
import random
import config
import pymysql
import requests
import interface
import pywinauto
import subprocess
from lxml import etree
from datetime import datetime
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys


class Aliexpress(object):
    def __init__(self):
        user_name, port = self.judge_account()
        print(user_name, port)
        self.kill_process(port)
        if user_name != 0:
            self.option = webdriver.ChromeOptions()
            # self.option.add_argument(
            #     r"--user-data-dir=C:\Users\Administrator\AppData\Local\Google\Chrome\User Data")  # 浏览器路径
            self.option.add_argument(fr"--user-data-dir=C:\Google\Google_config\{user_name}")  # 浏览器路径
            # self.option.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
            # self.option.binary_location = r'C:\Google\Chrome\Application\chrome.exe'
            self.option.add_argument(f'--window-position={20},{20}')
            self.option.add_argument(f'--window-size={1300},{900}')
            self.option.add_argument(f'--remote-debugging-port={port}')
            # self.option.add_experimental_option("debuggerAddress", f"127.0.0.1:{self.port}")
            self.option.add_experimental_option('excludeSwitches', ['enable-automation'])
            self.option.add_experimental_option('useAutomationExtension', False)
            self.driver = webdriver.Chrome(options=self.option)
            self.execute()
            self.driver.get("https://gsp.aliexpress.com/apps/im/window")
            time.sleep(1)
            ip = interface.get_ip()
            print("ip-----", ip)
            if "login" in self.driver.current_url:
                try:
                    self.user_login(user_name)
                    state = "登录成功"
                except Exception as e:
                    print("登录出错了。。", e)
                    state = "登录失败"
                interface.run_state_interface(ip, state)
            else:
                state = "登录成功"
                interface.run_state_interface(ip, state)
            print(self.driver.current_url)

    def kill_process(self, port):
        """查询指定端口对应的进程并杀死"""
        pids = os.popen(f"netstat -ano | findstr {port}").readlines()
        print("进程", type(pids), pids)
        for pid in pids:
            pid = re.findall(r"\s(\d+)\n", pid)[0]
            print(pid)
            os.popen(f'taskkill /T /F /PID {pid}')

    def judge_account(self):
        """判断账户"""
        file_name = os.path.split(__file__)[-1].split(".")[0]
        print(file_name)
        file = open('users.txt', 'r')
        contexts = file.readlines()
        print(contexts)
        if file_name == "aliexpress_chat":
            user_name = contexts[0].replace("\n", "")
            port = 5000
        elif file_name == "aliexpress_chat1":
            user_name = contexts[1].replace("\n", "")
            port = 5001
        elif file_name == "aliexpress_chat2":
            user_name = contexts[2].replace("\n", "")
            port = 5002
        elif file_name == "aliexpress_chat3":
            user_name = contexts[3].replace("\n", "")
            port = 5003
        elif file_name == "aliexpress_chat4":
            user_name = contexts[4].replace("\n", "")
            port = 5004
        elif file_name == "aliexpress_chat5":
            user_name = contexts[5].replace("\n", "")
            port = 5005
        elif file_name == "aliexpress_chat6":
            user_name = contexts[6].replace("\n", "")
            port = 5006
        elif file_name == "aliexpress_chat7":
            user_name = contexts[7].replace("\n", "")
            port = 5007
        elif file_name == "aliexpress_chat8":
            user_name = contexts[8].replace("\n", "")
            port = 5008
        elif file_name == "aliexpress_chat9":
            user_name = contexts[9].replace("\n", "")
            port = 5009
        else:
            user_name, port = 0, 0
            print("账户判断错误")
        return user_name, port

    def execute(self):
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """
            Object.defineProperty(navigator, 'webdriver', {
              get: () => false
            })
          """
        })
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """() =>{ window.navigator.chrome = { runtime: {},  }; }"""})
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """() =>{ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); }"""})
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """() =>{ Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5,6], }); }"""})
        # self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        #     "source": """() => {alert (window.navigator.webdriver)}"""})

    def quit_chrome(self):
        p = subprocess.Popen("cmd.exe /c" + r"C:\code\chrome.bat", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        curline = p.stdout.readline()
        while (curline != b''):
            curline = p.stdout.readline()
            p.wait()

    def user_login(self, user_name):
        """需要登录"""
        self.driver.get("https://login.aliexpress.com/")
        # self.driver.get("https://login.aliexpress.com/seller.htm")
        time.sleep(2)
        pp = self.driver.find_element(By.XPATH, '//*[@id="fm-login-id"]').get_attribute("value")
        print("((((((((((", pp)
        if pp == "":
            print("没有登陆过")
        password = interface.get_password_interface(user_name)
        input_user = self.driver.find_element(By.XPATH, '//*[@id="fm-login-id"]')
        input_user.click()
        input_user.send_keys(Keys.CONTROL, "a")
        input_user.send_keys(Keys.DELETE)
        input_user.send_keys(user_name)
        time.sleep(1)
        input_password = self.driver.find_element(By.XPATH, '//*[@id="fm-login-password"]')
        input_password.click()
        input_password.send_keys(Keys.CONTROL, "a")
        input_password.send_keys(Keys.DELETE)
        input_password.send_keys(password)
        time.sleep(1)
        try:
            self.driver.find_element(By.XPATH, '//*[@type="submit"]').click()  # 点击登录
        except:
            try:
                self.driver.find_element(By.XPATH, '//*[@id="fm-login-submit"]').click()
            except:
                try:
                    self.driver.find_element(By.XPATH, '//*[@type="submit"]//span').click()
                except:
                    self.driver.find_element(By.XPATH, '//*[contains(text(),"登录")]').send_keys(Keys.ENTER)
        time.sleep(2)
        # //*[@class="comet-alert-message"]
        # 你输入的密码和账户名不匹配，如果你近期修改过密码，请使用新密码登录
        password = self.driver.find_elements(By.XPATH, '//div[@class="comet-alert-message"]')
        if password:
            print("密码正确")
        else:
            print("密码错误")
            # password = interface.get_password_interface(user_name)
        # 验证码-------
        if "Please slide to verify" in self.driver.page_source:
            print(self.driver.page_source)
            print("验证码........")
            # self.validation()

    def unread_data(self, account_name):
        """点击未读数据"""
        try:
            # self.driver.find_element(By.CLASS_NAME, "im-components-checkbox").click()  # 点击未读取的
            self.driver.find_element(By.CLASS_NAME, "im-components-checkbox-label").click()  # 点击未读取的
        except Exception as e:
            print("点击未读消息", e)
            self.driver.find_element(By.CLASS_NAME, "im-components-checkbox-label ").click()
        while True:
            try:
                title_name = self.driver.find_element(
                    By.XPATH, '//div[@class="virtualize-box"]//div[@class="content"]//div[@class="title-name"]').text  # 买家名称
            except:
                break
            try:
                unread_sum = int(self.driver.find_element(
                    By.XPATH, '//div[@class="virtualize-box"]//div[@class="content"]//span[@class="badge"]').text)  # 未读数量
            except:
                unread_sum = 0
            self.driver.find_element(By.XPATH, f'//*[contains(text(),"{title_name}")]').click()
            time.sleep(2)
            # self.driver.find_element(By.XPATH, '//div[@class="message-content"]').click()
            # time.sleep(2)
            message_row = self.driver.find_elements(
                By.XPATH, '//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-0")]')
            for row in reversed(message_row):
                row.click()
            style = self.driver.find_element(
                By.XPATH, '//div[@class="message-content"]//div[@class="scrollbar-thumb"]').get_attribute("style")
            print(style)
            height = re.findall(r"height: (.*?)px", style)[0]
            # top = int(re.findall(r"top: (.*?)px",style)[0])
            print(height)
            # print(top)
            js = f'document.getElementsByClassName("scrollbar-thumb")[2].style="height: {height}px; top: -100px;"'
            print(js)
            self.driver.execute_script(js)  # 执行js语句
            self.aliexpress(self.driver.page_source, title_name, account_name, unread_sum)

    def not_reply(self, account_name):
        """未回复数据"""
        try:
            # pps = self.driver.find_elements(By.CLASS_NAME, "im-components-checkbox-inner")  # 点击未读取的
            # print(len(pps), pps)
            # print(pps[2].text)
            # pps[2].click()
            self.driver.find_element(
                By.XPATH, '//div[@class="switch-item"][2]//span[@class="im-components-checkbox "]').click()  # 未回复
        except Exception as e:
            print("点击回复消息", e)
            self.driver.find_element(
                By.XPATH, '//div[@class="switch-item"][2]//span[@class="im-components-checkbox"]').click()
        # //div[@class="virtualize-box"]//div[@class="title-name"]
        title_names = self.driver.find_elements(By.XPATH, '//div[@class="virtualize-box"]//div[@class="title-name"]')
        for title_name in title_names:
            title_name = title_name.text
            print("未回复的", title_name)
        #     self.driver.find_element(By.XPATH, f'//*[contains(text(),"{title_name}")]').click()
        #     time.sleep(2)
        #     message_row = self.driver.find_elements(
        #         By.XPATH, '//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-0")]')
        #     for row in reversed(message_row):
        #         row.click()
        #     style = self.driver.find_element(
        #         By.XPATH, '//div[@class="message-content"]//div[@class="scrollbar-thumb"]').get_attribute("style")
        #     height = re.findall(r"height: (.*?)px", style)[0]
        #     js = f'document.getElementsByClassName("scrollbar-thumb")[2].style="height: {height}px; top: -100px;"'
        #     print(js)
        #     self.driver.execute_script(js)  # 执行js语句
        #     self.aliexpress(self.driver.page_source, title_name, account_name)

    def cookies_data(self):
        """获取cookie 提取登录账户名称"""
        cookies = {cookie['name']: cookie['value'] for cookie in self.driver.get_cookies()}
        # print(type(cookies), cookies)
        account_name = "".join(re.findall(r"rmb_pp=(.*?)&", str(cookies)))
        if not account_name:
            account_name = "".join(re.findall(r"rmb_pp=(.*)", str(cookies)))
        print("值", account_name)
        return account_name

    def search_user(self, code_id, mid, did, content, content_type, account_name, merchanr_name, buyer_name):
        """搜索指定买家"""
        input_data = self.driver.find_element(By.XPATH, '//input[@class="simple-input"]')
        input_data.click()
        input_data.send_keys(Keys.CONTROL, "a")
        input_data.send_keys(Keys.DELETE)
        input_data.send_keys(buyer_name)
        # self.driver.find_element(By.XPATH, '//input[@class="simple-input"]').send_keys(buyer_name)  # .clear()
        self.driver.find_element(
            By.XPATH, '//div[@class="ae-search-panel user-name"]//li[@class="tab-item selected"]').click()
        # //div[@class="session-item active-false ripple"][1]//span[contains(text(),"US shopper")]  //div[@class="date"]
        self.driver.find_element(By.XPATH, f'//span[contains(text(),"{buyer_name}")]').click()
        time.sleep(1)
        try:
            if content_type == 1:
                self.driver.find_element(
                    By.XPATH, '//div[@class="message-fields__input"]/textarea').send_keys(content)
                # textarea.send_keys(content)
                # textarea.click()
                # textarea.send_keys(Keys.CONTROL, "Enter")
                # textarea.send_keys(Keys.CONTROL, "a")
                # textarea.send_keys(Keys.CONTROL, "ENTER")
                try:
                    self.driver.find_element(
                        By.XPATH, '//div[@class="im-icon im-icon-paper-plane im-icon-normal"]').click()  # 发送
                except:
                    self.driver.find_element(
                        By.XPATH, '//div[@class="message-fields__input"]/textarea').send_keys(content)
                    self.driver.find_element(
                        By.XPATH, '//div[@class="im-icon im-icon-paper-plane im-icon-normal"]').click()  # 发送
            elif content_type == 2:
                self.upload_img(content)
            elif content_type == 3:
                self.upload_video(content)
            else:
                pass
            for i in range(10):
                whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
                if whether:
                    time.sleep(0.5)
                else:
                    break
            else:
                whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
            # //div[@class="message-read-type"]//i//@class
            # whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
            # if whether:
            #     time.sleep(1)
            #     whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
            #     if whether:
            #         time.sleep(2)
            #         whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
            #         if whether:
            #             time.sleep(3)
            #             whether = self.driver.find_elements(By.XPATH, '//div[@class="message-read-type"]//i')
            print("转不转----", type(whether), whether)
            print("-----", type(content_type), content_type)
            # if whether == []:
            if not whether:
                success = True
            else:
                success = False
        except Exception as did:
            print("发送失败。。。。。。。", did)
            success = False
        if content_type != 1 and content_type != 2 and content_type != 3:
            print("**********")
            success = False
        interface.send_message_interface(code_id, mid, did, success, account_name, merchanr_name, buyer_name)

    def upload_img(self, content):
        """上传图片"""
        image = requests.get(content).content
        time_stamp = int(time.time())
        suffix = content.split('.')[-1]
        img_name = str(time_stamp) + "." + suffix
        print(img_name, ' 正在保存...')
        with open(f'../imgs/{img_name}', 'wb')as fp:
            fp.write(image)
            time.sleep(0.5)
        self.driver.find_element(
            By.XPATH, '//div[@class="message-fields__box"]//*[@class="im-icon im-icon-image im-icon-small"]').click()
        time.sleep(1)
        # 使用pywinauto来选择文件
        app = pywinauto.Desktop()
        # 选择文件上传的窗口
        dlg = app["打开"]
        # 选择文件地址输入框，点击激活
        # dlg["Toolbar3"].click()
        # 键盘输入上传文件的路径
        # send_keys(r"C:\imgs")
        # 键盘输入回车，打开该路径
        # send_keys("{VK_RETURN}")
        # 选中文件名输入框，输入文件名
        dlg["文件名(&N):Edit"].type_keys(fr"C:\imgs\{img_name}")
        # 点击打开
        dlg["打开(&O)"].click()
        time.sleep(1)
        self.driver.find_element(
            By.XPATH, '//button[@class="im-components-btn im-components-btn-primary im-components-btn-medium"]').click()

    def upload_video(self, content):
        """上传视频"""
        video = requests.get(content).content
        time_stamp = int(time.time())
        with open(f"../video/{time_stamp}.mp4", "wb") as f:
            f.write(video)
            time.sleep(1)
        self.driver.find_element(
            By.XPATH, '//div[@class="message-fields__box"]//*[@class="im-icon im-icon-video im-icon-small"]').click()
        time.sleep(1)
        # 使用pywinauto来选择文件
        app = pywinauto.Desktop()
        # 选择文件上传的窗口
        dlg = app["打开"]
        # 选中文件名输入框，输入文件名
        dlg["文件名(&N):Edit"].type_keys(fr"C:\video\{time_stamp}.mp4")
        # 点击打开
        dlg["打开(&O)"].click()
        time.sleep(1)
        self.driver.find_element(
            By.XPATH, '//button[@class="im-components-btn im-components-btn-primary im-components-btn-medium"]').click()

    def send_message(self, account_name):
        db = pymysql.connect(host=config.host, port=3306, db='sale', user=config.user, password=config.password,
                             charset='utf8')
        cursor = db.cursor()
        sql = f"""SELECT id,mid,did,content,content_type,account_name,merchanr_name,buyer_name FROM aliexpress_need_send_msg
                                where account_name = "{account_name}" 
                                ORDER BY create_time asc"""
        cursor.execute(sql)
        list_code = cursor.fetchall()
        print(len(list_code), list_code)
        for codes in list_code:
            code_id = codes[0]
            mid = codes[1]
            did = codes[2]
            content = codes[3]
            content_type = codes[4]
            account_name = codes[5]
            merchanr_name = codes[6]
            buyer_name = codes[7]
            self.search_user(code_id, mid, did, content, content_type, account_name, merchanr_name, buyer_name)  # 搜索指定买家
        db.close()

    def aliexpress(self, response, title_name, account_name, unread_sum):
        all_list = []
        soup = etree.HTML(response)
        list_class = soup.xpath(
            '//div[@class="message-content"]//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")]/@class')
        num = 0
        for name in list_class:
            num += 1
            if "user-type-0" in name:
                chat_times = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="lzd-system-text"]')
                print(len(chat_times))
                for times in chat_times:
                    name_time = times.xpath('string(.)').replace("\n", " ")
                    if "昨日" in name_time:
                        print(datetime.now().day - 1)
                        print(str(datetime.now().day - 1) + "/" + str(datetime.now().month))
                        name_time = name_time.replace("昨日",
                                                      str(datetime.now().day - 1) + "/" + str(datetime.now().month))
                    print("时间", name_time)
                    all_list.append({"chat_time": name_time})
            elif "user-type-11 row-card-text" in name or "user-type-11 row-card-action" in name:
                names1 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="lzd-message-text"]')
                for names in names1:
                    name1 = names.xpath('string(.)').replace("\n", " ").replace('"', '')
                    print("买家", name1)
                    all_list.append({"buyers": name1})
            elif "user-type-11 row-card-image" in name:
                names1 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="background-default card-img"]//@style')
                for names in names1:
                    # name1 = re.sub(r'.*url\("', '', names).replace("\");", "")
                    name1 = re.findall(r'\("(.*)"\)', names)[0]
                    print("买家", name1)
                    all_list.append({"buyers_img": name1})
            elif "user-type-11 row-card-order" in name:
                names1 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="card-order-v2 message-card-dx"]')
                for names in names1:
                    name1 = names.xpath('string(.)').replace("\n", " ").replace("Status", " Status")
                    print("买家", name1)
                    all_list.append({"buyers_order": name1})
            elif "user-type-11 row-card-video" in name:
                videos = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//video[@class="video"]//@src')
                for video in videos:
                    print("买家视频", video)
                    all_list.append({"buyers_video": video})
            elif "user-type-11 row-card-product" in name:
                buyers_product = self.product(soup, num)
                all_list.append({"buyers_product": buyers_product})
            elif "user-type-12 row-card-text" in name or "user-type-12 row-card-action" in name:
                names2 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="lzd-message-text"]')
                for names in names2:
                    name2 = names.xpath('string(.)').replace("\n", " ").replace('"', '')
                    print("卖家", name2)
                    all_list.append({"seller": name2})
            elif "user-type-12 row-card-image" in name:
                print("来了" * 10, num)
                names2 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="background-default card-img"]//@style')
                for names in names2:
                    # name2 = re.sub(r'.*url\("', '', names).replace("\");", "")
                    print(names)
                    name2 = re.findall(r'\("(.*)"\)', names)[0]
                    print("卖家", name2)
                    all_list.append({"seller_img": name2})
            elif "user-type-12 row-card-order" in name:
                names1 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="card-order-v2 message-card-dx"]')
                for names in names1:
                    name1 = names.xpath('string(.)').replace("\n", " ").replace("Status", " Status")
                    print("卖家", name1)
                    all_list.append({"seller_order": name1})
            elif "user-type-12 row-card-video" in name:
                videos = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//video[@class="video"]//@src')
                for video in videos:
                    print("卖家视频", video)
                    all_list.append({"seller_video": video})
            elif "user-type-12 row-card-product" in name:
                buyers_product = self.product(soup, num)
                all_list.append({"buyers_product": buyers_product})
            elif "user-type-12 row-card-system" in name:
                names1 = soup.xpath(
                    f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="lzd-system-text"]')
                for names in names1:
                    name1 = names.xpath('string(.)').replace("\n", " ")
                    print("关注店铺/撤回消息", name1)
                    all_list.append({"message": name1})
            else:
                print("内容" * 5, name)
                pass
        country = soup.xpath('//div[contains(@class,"user-flag intl-css_flag")]/../text()')
        merchanr_name = soup.xpath('//*[@class="im-page-header-switch-nickname"]//text()')
        item = {title_name: all_list, "user_name": title_name, "country": country[0], "account_name": account_name,
                "merchanr_name": merchanr_name[0], "unread_sum": unread_sum}
        print("~~~~~~~~~~~~")
        interface.content_interface(item)
        print(json.dumps(item, ensure_ascii=False))

    def product(self, soup, num):
        buyers_product = []
        product_dict = {}
        product_img = soup.xpath(
            f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="card-product-v2 message-card-dx"]//@src')
        product_dict.update({"img": product_img[0]})
        product_name = soup.xpath(
            f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="card-product-v2-name"]')
        name1 = product_name[0].xpath('string(.)').replace("\n", " ")
        product_dict.update({"name": name1})
        product_price = soup.xpath(
            f'//div[@class="scroll-content"]//div[contains(@class,"message-row user-type-")][{num}]//div[@class="card-product-v2-price"]')
        price = product_price[0].xpath('string(.)').replace("\n", " ")
        product_dict.update({"price": price})
        buyers_product.append(product_dict)
        return buyers_product

    def validation(self):
        """验证码"""
        print("验证码")
        try:
            self.driver.implicitly_wait(5)
            drag1 = self.driver.find_element(By.ID, 'nc_1_n1z')
            ActionChains(self.driver).click_and_hold(drag1).perform()
            # tracks = random.sample(range(30, 90), 7)
            tracks = []
            count = 0
            while True:
                nums = random.randint(1, 90)
                count = count + nums
                tracks.append(nums)
                if count >= 310:
                    break
            second = datetime.now().second
            if (second % 2) == 0:
                tracks.sort(reverse=True)
            else:
                tracks.sort()
            for x in tracks:
                ActionChains(self.driver).move_to_element(drag1).perform()
                ActionChains(self.driver).move_by_offset(xoffset=x, yoffset=0).perform()
            time.sleep(0.5)
            ActionChains(self.driver).release().perform()
            time.sleep(3)
            # self.driver.implicitly_wait(10)
            self.num += 1
            if self.num >= 10:
                self.num = 0
                self.driver.quit()
                time.sleep(10)
                option = webdriver.ChromeOptions()
                option.add_argument(f'--window-position={20},{20}')
                option.add_argument(f'--window-size={1300},{1000}')

                option.add_experimental_option('excludeSwitches', ['enable-automation'])
                option.add_experimental_option('useAutomationExtension', False)
                # option.add_argument(f'--user-agent={random.choice(config.USER_AGENT_LIST)}')
                # option.add_extension(proxyMeta)
                self.driver = webdriver.Chrome(options=option)
                self.execute()
                self.driver.get("https://www.aliexpress.com/")
                js = "var q=document.documentElement.scrollTop=1500"
                self.driver.execute_script(js)
                time.sleep(2)
                try:
                    urls = self.driver.find_elements(
                        By.XPATH, '//*[contains(@href,"www.aliexpress.com")]')[0].get_attribute("href")
                except:
                    self.driver.refresh()
                    self.driver.execute_script(js)
                    time.sleep(2)
                    urls = self.driver.find_elements(
                        By.XPATH, '//*[contains(@href,"www.aliexpress.com")]')[-1].get_attribute("href")
                self.driver.get(urls)
                time.sleep(2)
            if "Please slide to verify" in self.driver.page_source:
                # self.driver.refresh()
                # self.driver.get(url)
                self.validation()
        except Exception as e:
            print("滑块异常", e)
            time.sleep(1)
            if "Please slide to verify" in self.driver.page_source:
                # self.driver.refresh()
                # self.driver.get(url)
                self.validation()
            elif "reachable" in str(e):
                # else:
                print("浏览器异常暂停10秒")
                time.sleep(10)
                self.driver.quit()
                option = webdriver.ChromeOptions()
                # self.option.add_argument(r"--user-data-dir=C:\code\Google\merchant")
                option.add_argument(f'--window-position={20},{20}')
                option.add_argument(f'--window-size={1300},{1000}')
                option.add_experimental_option('excludeSwitches', ['enable-automation'])
                option.add_experimental_option('useAutomationExtension', False)
                # option.add_argument(f'--user-agent={random.choice(config.USER_AGENT_LIST)}')
                # option.add_extension(proxyMeta)
                self.driver = webdriver.Chrome(options=option)
                self.execute()
                self.driver.get("https://www.aliexpress.com/")
                js = "var q=document.documentElement.scrollTop=1500"
                self.driver.execute_script(js)
                time.sleep(2)
                try:
                    urls = self.driver.find_elements(
                        By.XPATH, '//*[contains(@href,"www.aliexpress.com")]')[0].get_attribute("href")
                except:
                    self.driver.refresh()
                    self.driver.execute_script(js)
                    time.sleep(2)
                    urls = self.driver.find_elements(
                        By.XPATH, '//*[contains(@href,"www.aliexpress.com")]')[-1].get_attribute("href")
                self.driver.get(urls)
                time.sleep(2)
            elif "attached to the" in str(e):
                print("%%%%%%")
                pass
            else:
                if "霸下通用 web 页面-验证码" in self.driver.page_source:
                    self.validation()

    def run(self):
        # content = "https://vd2.bdstatic.com/mda-mm84m7bcuefvyf07/720p/h264/1639019800396284112/mda-mm84m7bcuefvyf07.mp4"
        # self.upload_video(content)
        # try:
            account_name = self.cookies_data()  # 获取cookie 提取登录账户名称
            while True:
                print("未读----")
                if "login" in self.driver.current_url:
                    print("需要登录")
                    self.driver.quit()
                    break
                self.unread_data(account_name)  # 获取未读数据
                time.sleep(5)
                # self.driver.refresh()
                self.driver.get("https://gsp.aliexpress.com/apps/im/window")
                for i in range(150):
                    print("等待，查询数据中")
                    time.sleep(10)
                    self.send_message(account_name)
                # self.driver.refresh()
                self.driver.get("https://gsp.aliexpress.com/apps/im/window")
                print("未回复----")
                self.not_reply(account_name)
                time.sleep(5)
                now = datetime.now()
                # 大于等于21点 小于等于7点 退出
                if 21 <= now.hour or now.hour <= 7:
                    print(now.hour)
                    print("退出")
                    self.driver.quit()
                    break
        # except Exception as e:
        #     print("程序异常----", e)
        #     ip = interface.get_ip()
        #     print("ip-----", ip)
        #     state = "登录失败"
        #     interface.run_state_interface(ip, state)


if __name__ == '__main__':
    now = datetime.now()
    print(now.hour)
    # 小于等于21点 大于等于8点
    if 21 >= now.hour >= 8:
        fps = Aliexpress()
        fps.run()
